package com.yiwei.jmx.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.yiwei.jmx.R;
import com.yiwei.jmx.adapter.YmdBorrowMenuAdapter;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.DealIndexAuthorBean;
import com.yiwei.jmx.api.bean.DealIndexDetailBean;
import com.yiwei.jmx.api.model.DealIndexDetailModel;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.event.ChangeHomePageEvent;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.NumAnim;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.Spans;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.MyProgressView;
import com.yiwei.jmx.view.SelectMenuTipsDilaog;
import com.yiwei.jmx.view.V19FrameLayout;
import com.yiwei.jmx.view.YmdLoadingDialog;
import com.yiwei.jmx.view.YmdServiceDialog;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class YmdBorrowActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_banner)
    ImageView imgBanner;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.progress_view)
    MyProgressView progressView;
    @BindView(R.id.txt_progress_tips)
    TextView txtProgressTips;
    @BindView(R.id.txt_info_left)
    TextView txtInfoLeft;
    @BindView(R.id.txt_info_right)
    TextView txtInfoRight;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.txt_bottom_tips)
    TextView txtBottomTips;
    @BindView(R.id.layout_has_edu)
    LinearLayout layoutHasEdu;
    @BindView(R.id.txt_no_edu)
    TextView txtNoEdu;
    private Unbinder unbiner;
    private SelectMenuTipsDilaog selectMenuTipsDilaog;
    private YmdBorrowMenuAdapter adapter;
    private DealIndexDetailModel.DataBean totalData;
    private String company_id;
    private YmdLoadingDialog ymdLoadingDialog;
    private String channel_id;

    private float progress = 0;

    private static final int TIME = 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 100) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
//            Log.i("dasdadsadasda", millisUntilFinished + "进度"+(millisUntilFinished / 100)+"后面："+(10 % (millisUntilFinished / 100))+"最后"+progress * (10 % (millisUntilFinished / 100)));

            progressView.setProgressSec(progress  * (10 - (millisUntilFinished / 100)));
        }

        @Override
        public void onFinish() {
            progressView.setProgressSec(progress * 10);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ymd_borrow);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        company_id = getIntent().getStringExtra("company_id");
        channel_id = getIntent().getStringExtra("channel_id");
        selectMenuTipsDilaog = new SelectMenuTipsDilaog(this);
        ymdLoadingDialog = new YmdLoadingDialog(YmdBorrowActivity.this);
        ymdLoadingDialog.setOnSelect(new YmdLoadingDialog.OnSureListener() {
            @Override
            public void onSure() {
                getDealIndexDetail(company_id);
            }
        });
        txtRight.setText("提智信分");
        txtRight.setTextColor(0xff0072FF);
        txtRight.setVisibility(View.VISIBLE);
//        new YmdLoadingDialog(this);
        adapter = new YmdBorrowMenuAdapter(this);
        list.setAdapter(adapter);
        list.setLayoutManager(new GridLayoutManager(this, 3));


        getDealIndexDetail(company_id);
    }

    private void showFailDialog() {
        selectMenuTipsDilaog.showTwoSelectData("主人", R.mipmap.dialog_tips_success, "您暂时没有额度，因为没有智信分！", "我再看看", "获取智信分");
        selectMenuTipsDilaog.setOnChooseListener(new SelectMenuTipsDilaog.OnChooseListener() {
            @Override
            public void onLeft() {
                selectMenuTipsDilaog.dismiss();
            }

            @Override
            public void onRight() {
                selectMenuTipsDilaog.dismiss();
                Util.startActivity(YmdBorrowActivity.this, IdentityCenterActivity.class);
                finish();
            }
        }).show();
    }

    private void showGetIngDialog() {
        selectMenuTipsDilaog.showTwoSelectData("", 0, "本次授权未能获得额度请24小时之后再次授权试试或者提高智信分试试", "取消", "提智信分");
        selectMenuTipsDilaog.setOnChooseListener(new SelectMenuTipsDilaog.OnChooseListener() {
            @Override
            public void onLeft() {
                selectMenuTipsDilaog.dismiss();
            }

            @Override
            public void onRight() {
                selectMenuTipsDilaog.dismiss();
                Util.startActivity(YmdBorrowActivity.this, IdentityCenterActivity.class);
                finish();
            }
        }).show();
    }

    private void getDealIndexDetail(String company_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        DealIndexDetailBean bean = new DealIndexDetailBean();
        bean.company_id = company_id;
        bean.channel_id = channel_id;
        Api.api_service.getDealIndexDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setDealIndexDetailData(result.data);
                });
    }

    private void getDealIndexAuthor(String company_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        DealIndexAuthorBean bean = new DealIndexAuthorBean();
        bean.company_id = company_id;
        bean.channel_id = channel_id;
        Api.api_service.getDealIndexAuthor(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
//                    getDealIndexAuthor(company_id);
                    if (result.getStatus() == 1) {
                        ymdLoadingDialog.show();
                    } else {
                        ToastUtil.makeText(this, result.getMsg());
                    }

                });
    }

    private void setDealIndexDetailData(DealIndexDetailModel.DataBean data) {
        totalData = data;
        adapter.update(data.item);
        txtTitle.setText(data.name);
        Glide.with(this).load(data.banner).error(R.mipmap.img_ymd_banner_default).into(imgBanner);
        Spanned txt_info_left = Spans.with(this).font(data.money_min + "~" + data.money_max, getResources().getDimensionPixelSize(R.dimen.x36), 0xff566F8E).
                font("\n额度范围(元)", getResources().getDimensionPixelSize(R.dimen.x24), 0xff566F8E).build();
        txtInfoLeft.setText(txt_info_left);

        Spanned txt_info_right = Spans.with(this).font(data.rate + "%", getResources().getDimensionPixelSize(R.dimen.x36), 0xff566F8E).
                font("\n综合年化利率", getResources().getDimensionPixelSize(R.dimen.x24), 0xff566F8E).build();
        txtInfoRight.setText(txt_info_right);

        if (data.is_auth.equals("1")) {
            layoutHasEdu.setVisibility(View.VISIBLE);
            txtNoEdu.setVisibility(View.GONE);
//            progressView.setProgressSec(Float.valueOf(data.auth_money), Float.valueOf(data.money_max));
            progress = Float.valueOf(data.auth_money) / Float.valueOf(data.money_max) / 10;
            timer.start();
//            Spanned txt_progress = Spans.with(this).font(data.auth_money, getResources().getDimensionPixelSize(R.dimen.x72), 0xff0072FF).style(Typeface.BOLD).
//                    font("\n当前额度(元)", getResources().getDimensionPixelSize(R.dimen.x24), 0xff566F8E).build();
//            txtProgressTips.setText(txt_progress);

            NumAnim.startAnim(txtProgressTips, Float.valueOf(data.auth_money), 1000);     //设置滚动动画持续1秒
            btnSubmit.setText("申请借款");
        } else {
            layoutHasEdu.setVisibility(View.GONE);
            txtNoEdu.setVisibility(View.VISIBLE);
            progressView.setProgressSec(0, 100);
            btnSubmit.setText("授权获取额度");
        }
        txtBottomTips.setText("本服务由" + data.lender + "提供");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.txt_right, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                EventBus.getDefault().post(new ChangeHomePageEvent(2));
                finish();
                break;
            case R.id.btn_submit:
                if (totalData == null) {
                    getDealIndexDetail(company_id);
                    return;
                }
                if (totalData.is_auth.equals("0")) {
                    new YmdServiceDialog(this).setData(totalData.name).setOnSelect(new YmdServiceDialog.OnSureListener() {
                        @Override
                        public void onSure() {
                            getDealIndexAuthor(company_id);
                        }
                    }).show();
                } else {
                    Intent intent = new Intent(this, BorrowStepActivity.class);
                    intent.putExtra("data", totalData);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    finish();
                }
                break;
        }
    }
}
